/**
 * @brief  初始化和上位机之间通讯的串行接口。
 * @author 巴桂阳
 * @date   2024/12/20
 */

#include "drv_host.h"

/* 绑定硬件通讯口 */
bsp_uart_t *host_com = &dev_tree.usart0;
bsp_gpio_t *rde_pin  = &dev_tree.gpioa_8;

/**
 * @brief 驱动接口申明
 */
ES_STATIC ES_INT32 host_read(es_drv_t *dev, ES_VOID *buffer, ES_INT32 size);
ES_STATIC ES_INT32 host_write(es_drv_t *dev, ES_CONST_VOID *buffer, ES_INT32 size);
ES_STATIC ES_INT32 host_ioctl(es_drv_t *dev, ES_INT32 cmd, ES_VOID *args);


/**
 * @brief  串口空闲中断回调函数
 * @param  rec_len 串口接收的数据长度
 * @author bagy
 * @date   2024/12/24
 */
ES_STATIC ES_VOID host_uart_idle_int(ES_U32 rec_len)
{
    /**
     * 写入消息到消息队列中
     * 重新使能DMA通道
     */

    bsp_dma_enable(&host_com->rx_dma);
}

/**
 * @brief 调试串口的读写驱动
 *
 * @details 绑定接口，用于设备的注册
 */
ES_STATIC es_ops_t host_ops = {
		.read  = host_read,
		.write = host_write,
		.ioctl = host_ioctl,
};

/**
 * @brief 调试串口设备的描述信息
 *
 * @details 配置设备ID及设备驱动
 */
ES_STATIC es_drv_t host_dev = {
		.id 	 = HOST_UART_ID,
		.drv_ops = &host_ops,
};

/**
 * @brief 串口发送数据。
 *
 * @param dev 设备结构体
 * @param buffer 发送的数据
 * @param size 发送的buffer长度
 *
 * @return 0:successfully.
 */
ES_STATIC ES_INT32 host_write(es_drv_t *dev, ES_CONST_VOID *buffer, ES_INT32 size)
{
    ES_ASSERT(dev != NULL);
    ES_ASSERT(buffer != NULL);
    ES_ASSERT(size < 1);

    bsp_uart_send_buff(host_com, (ES_U8 *)buffer, (ES_U32)size);

	return 0;
}

/**
 * @brief 读取串口数据
 *
 * @param dev 设备结构体
 * @param buffer 发送的数据
 * @param size 发送的buffer长度
 *
 * @return 0:successfully.
 */
ES_STATIC ES_INT32 host_read(es_drv_t *dev, ES_VOID *buffer, ES_INT32 size)
{

}

/**
 * @brief 通过该接口实现DMA半完成中断的关闭以及DMA缓冲区的配置
 *
 * @details 可通过cmd字段区分类型实现修改波特率等用户自定义的控制功能
 *
 * @param dev 设备结构体
 * @param cmd 命令
 * @param args 传入参数
 *
 * @return 0:successfully.
 */
ES_STATIC ES_INT32  host_ioctl(es_drv_t *dev, ES_INT32 cmd, ES_VOID *args)
{

	return ES_TRUE;
}

/**
 * @brief  上位机通信串口初始化，配置空闲中断回调函数
 * @author bagy
 * @date   2024/12/24
 */
//#pragma location =".es_drv_init.1"
__root void drv_host_config(void) 
{
    bsp_uart_config(host_com, host_uart_idle_int);

    	/* 注册成功 */
	if(es_drv_register(&host_dev) == ES_TRUE)
	{
		log_i("<%s> Device driver registration successful.\r\n", __func__);
	}
	else /* 注册失败 */
	{
		log_i("<%s> Failed to register device driver.\r\n", __func__);
	}
}
ES_INIT_EXPORT(drv_host_config, "2");


